<template>
  <div class="dryrun">
    <el-dialog
      v-bind="$attrs"
      width="1000px"
      v-on="$listeners"
      @close="handleClose"
      @open="handleOpen"
    >
      <template #title>
        <div>
          <span class="mr-2">{{ $t("flyparam.batch_operation") }}</span>
          <el-tooltip>
            <template #content>
              <div class="text-md" v-html="$t('flyparamter.batch_operation_help')"
            /></template>
            <i class="el-icon-question" />
          </el-tooltip></div
      ></template>
      <div class="dryrun-button-group">
        <button
          class="dryrun-header-button"
          :class="{ active: operationType === 1 }"
          @click="() => handleOperationChange(1)"
        >
          <svg-icon icon-class="upgrade" class-name="mr-2" />Update fields
        </button>
        <button
          class="dryrun-header-button"
          :class="{ active: operationType === 2 }"
          @click="() => handleOperationChange(2)"
        >
          <i class="el-icon-delete mr-2" />Delete
        </button>
      </div>
      <div style="padding-left: 30px">
        <!-- Conditions -->

        <div class="py-3">
          <div class="dryrun-condition">
            <h3 class="font-bold mb-3">
              {{ $t("flyparam.conditions") }}
              <el-tooltip placement="top">
                <template #content>
                  <div class="text-md" v-html="$t('flyparam.batch_operation_help2')"
                /></template>
                <i class="el-icon-question" />
              </el-tooltip>
            </h3>
            <el-form
              ref="conditionForm"
              :model="conditionForm"
              validate-on-rule-change
              @submit.native.prevent
            >
              <el-row
                v-for="(item, index) in _conditions"
                :key="index"
                class="text-center relative mb-3"
              >
                <el-col>
                  <div class="input-group">
                    <div
                      class="el-select-group"
                      :class="{
                        boolean: item.select && item.select.valueType === types.BOOLEAN,
                      }"
                    >
                      <el-select
                        v-if="index === 0"
                        v-model="tableId"
                        disabled
                        size="small"
                        :placeholder="$t('flyparam.select_table')"
                        @change="handleTableIdChange"
                      >
                        <el-option
                          v-for="table in profileTableList"
                          :key="table.id"
                          :label="table.name"
                          :value="table.id"
                        />
                      </el-select>
                      <el-select
                        v-else
                        v-model="item.conditionConnector"
                        size="small"
                        :placeholder="$t('flyparam.select_table')"
                      >
                        <el-option label="AND" :value="1" />
                        <el-option label="OR" :value="2" />
                      </el-select>
                      <el-form-item
                        :rules="[
                          {
                            validator: validateConditionParams,
                            trigger: 'blur',
                          },
                        ]"
                        :prop="'conditions.' + index + '.' + 'select'"
                      >
                        <el-select
                          v-model="item.select"
                          v-popover="`condition${index}`"
                          class="parameter-selector"
                          size="small"
                          value-key="label"
                          :placeholder="$t('common.please_select')"
                          @change="
                            (parameter) =>
                              handleParameterLabelChange(parameter, item, index)
                          "
                        >
                          <el-option
                            v-for="parameter in parameterLabels"
                            :key="parameter.label"
                            :value="{
                              label: parameter.label,
                              valueType: parameter.valueType,
                              rule: parameter.rule,
                              paramId: parameter.paramId,
                              ...parameter,
                            }"
                            :disabled="parameter.disabled"
                            :label="parameter.label"
                          >
                            <div v-if="parameter.disabled" class="flex items-center">
                              <span class="flex-1 mr-4">
                                {{ parameter.label }}
                              </span>
                              <el-tooltip
                                :content="$t('flyparam.dryrun_restricted')"
                                placement="top"
                              >
                                <i class="el-icon-question" style="color: #606266" />
                              </el-tooltip>
                            </div>
                            <span v-else>{{ parameter.label }}</span>
                          </el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item
                        :prop="'conditions.' + index + '.' + 'conditionMatcher'"
                        :rules="[{ required: true, message: 'Required' }]"
                      >
                        <el-select
                          v-model="item.conditionMatcher"
                          size="small"
                          :placeholder="$t('common.please_select')"
                          @change="
                            () => {
                              item.value = '';
                            }
                          "
                        >
                          <el-option
                            v-for="option in conditionOptions[item.select.valueType] ||
                            conditionOptions.others"
                            :key="option.value"
                            :label="option.label"
                            :value="option.value"
                          />
                        </el-select>
                      </el-form-item>
                    </div>
                    <el-form-item
                      v-if="item.select && item.select.valueType === types.BOOLEAN"
                    />
                    <el-form-item
                      v-else
                      :prop="'conditions.' + index + '.' + 'value'"
                      :rules="[
                        {
                          required: item.conditionMatcher !== 3,
                          message: $t('flyparam.required2'),
                        },
                      ]"
                    >
                      <template
                        v-if="item.select && item.select.valueType === types.REFERENCE"
                      >
                        <el-select
                          v-if="
                            item.parameter.table && item.parameter.table.tableType === 3
                          "
                          v-model="item.value"
                          v-loadmore="() => handleLoadMoreReference(item, 'conditions')"
                          multiple
                          :loading="valueSelectorLoading"
                          size="small"
                          class="input-group-right text-left"
                          @visible-change="
                            (visible) =>
                              fetchReferenceData(visible, true, item, 'conditions')
                          "
                        >
                          <el-option
                            v-for="value in referenceValues"
                            :key="value.$id[0]"
                            :label="value.$label[0]"
                            :value="value.$id[0]"
                          />
                        </el-select>
                        <el-select
                          v-else
                          v-model="item.value"
                          :popper-append-to-body="false"
                          multiple
                          size="small"
                          class="input-group-right object-table-select"
                          @click.native="
                            (e) => handleReferenceClick(e, item.id, 'conditions')
                          "
                        />
                      </template>
                      <el-date-picker
                        v-else-if="item.select && item.select.valueType === types.DATE"
                        v-model="item.value"
                        :disabled="item.conditionMatcher === 3"
                        class="input-group-right"
                        :format="item.select.formatter"
                        :value-format="item.select.formatter"
                        type="date"
                        size="small"
                      />
                      <el-date-picker
                        v-else-if="
                          item.select && item.select.valueType === types.DATETIME
                        "
                        v-model="item.value"
                        :disabled="item.conditionMatcher === 3"
                        class="input-group-right"
                        :format="item.select.formatter"
                        :value-format="item.select.formatter"
                        type="datetime"
                        size="small"
                      />
                      <el-time-picker
                        v-else-if="item.select && item.select.valueType === types.TIME"
                        v-model="item.value"
                        :disabled="item.conditionMatcher === 3"
                        :format="item.select.formatter"
                        :value-format="item.select.formatter"
                        size="small"
                        style="width: 100%"
                      />
                      <el-input
                        v-else-if="item.select && item.select.valueType === types.FILE"
                        v-model="item.value"
                        :disabled="item.conditionMatcher === 3"
                        readonly
                        size="small"
                        class="input-group-right"
                        :placeholder="$t('flyparam.choose_file')"
                        @click.native="
                          (e) => handleFileUploadClick(e, item.id, 'condition')
                        "
                      />
                      <el-input
                        v-else
                        v-model="item.value"
                        :disabled="item.conditionMatcher === 3"
                        :placeholder="$t('common.please_input')"
                        size="small"
                        class="input-group-right"
                      />
                    </el-form-item>
                  </div>
                </el-col>
                <a
                  v-if="index > 0"
                  class="icon-btn icon-minus"
                  @click="() => removeCondition(index)"
                  >-</a
                >
                <a
                  v-if="index === 0 && _conditions.length < 5"
                  class="icon-btn icon-add"
                  @click="addCondition"
                  >+</a
                >
              </el-row>
            </el-form>
          </div>
        </div>

        <el-row v-loading="dryrunLoading" class="dryrun-result">
          <template>
            <el-col key="download-button" :span="4">
              <h2 v-show="showResult" class="search-result">Search Result</h2>
            </el-col>
            <el-col v-if="showResult" key="dryrun-result" :span="14" class="dryrun-col">
              <div class="flex items-center">
                <div class="flex items-center mr-5">
                  <div class="mr-3">
                    <i class="el-icon-success text-xl text-green-400" />
                  </div>
                  <div class="flex-grow">
                    <span
                      >{{ sucNum + failNum }} {{ $t("flyparam.entries_matched") }}</span
                    >
                  </div>
                </div>
                <div v-if="failNum > 0" class="flex items-center mr-5">
                  <div class="mr-3">
                    <i class="el-icon-date text-xl text-blue-400" />
                  </div>
                  <div class="flex-grow">
                    <span>{{ failNum }} {{ $t("flyparam.dryrun_schedule") }}</span>
                  </div>
                </div>
                <div class="dryrun-button__container">
                  <el-tooltip
                    v-if="downloadUrl.length > 0"
                    :content="$t('flyparam.download_result')"
                    placement="top"
                  >
                    <button size="small" class="dryrun-download" @click="download">
                      <i class="el-icon-download" />
                    </button>
                  </el-tooltip>
                </div>
              </div>
            </el-col>
          </template>
          <el-col :span="showResult ? 6 : 20">
            <div class="flex items-center justify-end">
              <div class="dryrun-button__container">
                <button
                  class="dryrun-dryrun-button"
                  type="primary"
                  @click="() => execDryrun(true)"
                >
                  <i v-if="dryrunLoading" class="el-icon-loading" /><i
                    v-else
                    class="el-icon-search mr-2"
                  />{{ $t("flyparam.testrun") }}
                </button>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- Operations -->
        <div class="mt-5 dryrun-operations">
          <h3 v-show="operationType === 1" class="font-bold mb-3">
            {{ $t("common.operation") }}
          </h3>
          <div>
            <el-form
              v-show="showOperations"
              ref="operationForm"
              :model="operationForm"
              validate-on-rule-change
              class="operation-form"
            >
              <el-row
                v-for="(item, index) in operations"
                :key="index"
                class="relative mb-3"
              >
                <el-col>
                  <div>
                    <el-form-item
                      :prop="'operations.' + index + '.' + 'select'"
                      :rules="[
                        {
                          validator: validateOperationSelect,
                          trigger: 'blur',
                        },
                      ]"
                    >
                      <el-select
                        v-model="item.select"
                        class="input-group-left"
                        size="small"
                        value-key="label"
                        :placeholder="$t('common.please_select')"
                        @change="
                          (parameter) =>
                            handleParameterLabelChange(parameter, item, index)
                        "
                      >
                        <el-option
                          v-for="parameter in filterSelectedParameter(item)"
                          :key="parameter.label"
                          :value="{
                            label: parameter.label,
                            valueType: parameter.valueType,
                            rule: parameter.rule,
                            paramId: parameter.paramId,
                            ...parameter,
                          }"
                          :label="parameter.label"
                        />
                      </el-select>
                      <span class="px-3">=</span>
                    </el-form-item>
                    <el-form-item
                      :prop="'operations.' + index + '.' + 'value'"
                      :rules="item.rule"
                    >
                      <template
                        v-if="item.select && item.select.valueType === types.REFERENCE"
                      >
                        <el-select
                          v-if="
                            item.parameter.table && item.parameter.table.tableType === 3
                          "
                          v-model="item.value"
                          v-loadmore="() => handleLoadMoreReference(item, 'operations')"
                          multiple
                          :loading="valueSelectorLoading"
                          size="small"
                          class="input-group-right"
                          @visible-change="
                            (visible) =>
                              fetchReferenceData(visible, true, item, 'operations')
                          "
                        >
                          <el-option
                            v-for="value in referenceValues"
                            :key="value.id[0]"
                            :label="value.$label[0]"
                            :value="value.$label[0]"
                          />
                        </el-select>
                        <el-select
                          v-else
                          v-model="item.value"
                          :popper-append-to-body="false"
                          multiple
                          size="small"
                          class="input-group-right object-table-select"
                          @click.native="
                            (e) => handleReferenceClick(e, item.id, 'operations')
                          "
                        />
                      </template>
                      <el-date-picker
                        v-else-if="item.select && item.select.valueType === types.DATE"
                        v-model="item.value"
                        class="input-group-right"
                        :format="item.select.formatter"
                        :value-format="item.select.formatter"
                        type="date"
                        size="small"
                      />
                      <el-date-picker
                        v-else-if="
                          item.select && item.select.valueType === types.DATETIME
                        "
                        v-model="item.value"
                        class="input-group-right"
                        :format="item.select.formatter"
                        :value-format="item.select.formatter"
                        type="datetime"
                        size="small"
                      />
                      <el-time-picker
                        v-else-if="item.select && item.select.valueType === types.TIME"
                        v-model="item.value"
                        :format="item.select.formatter"
                        :value-format="item.select.formatter"
                        size="small"
                        style="width: 100%"
                      />
                      <el-select
                        v-else-if="item.select && item.select.valueType === types.BOOLEAN"
                        v-model="item.value"
                        size="small"
                        class="input-group-right"
                      >
                        <el-option :label="$t('flyparam.true_option')" :value="true" />
                        <el-option :label="$t('flyparam.false_option')" :value="false" />
                      </el-select>
                      <el-input
                        v-else-if="item.select && item.select.valueType === types.FILE"
                        v-model="item.value"
                        readonly
                        size="small"
                        class="input-group-right"
                        :placeholder="$t('flyparam.choose_file')"
                        @click.native="
                          (e) => handleFileUploadClick(e, item.id, 'operation')
                        "
                      />
                      <el-input
                        v-else
                        v-model="item.value"
                        :placeholder="$t('common.please_input')"
                        size="small"
                        class="input-group-right"
                      />
                    </el-form-item>
                  </div>

                  <a
                    v-if="index > 0"
                    class="icon-btn icon-minus"
                    @click="() => removeOperation(index)"
                    >-</a
                  >
                  <a
                    v-if="index === 0 && operations.length < 10"
                    class="icon-btn icon-add"
                    @click="addOperation"
                    >+</a
                  >
                </el-col>
              </el-row>
            </el-form>
          </div>

          <!-- <div class="text-center py-3">
          <el-button size="small" type="primary" @click="addOperation">
            <i class="el-icon-plus mr-2" />{{ $t('flyparam.add_operation') }}
          </el-button>
        </div> -->
        </div>
      </div>
      <template #footer>
        <div>
          <el-button size="small" @click="$emit('update:model-value', false)">{{
            $t("common.cancel")
          }}</el-button>
          <el-button
            type="primary"
            size="small"
            :loading="confirmLoading"
            :disabled="!dryrunReady || sucNum === 0"
            @click="() => execDryrun(false)"
            >{{ $t("common.confirm") }}</el-button
          >
        </div>
      </template>
      <select-reference
        append-to-body
        v-model="selectReferenceVisible"
        :table-id="currentItem ? currentItem.refTableSchemaId : ''"
        :current-item="currentReference"
        :template-id="templateId"
        :dryrun="true"
        @confirm="(selections, ids) => handleSelectReferenceConfirm(selections, ids)"
      />

      <upload-file
        :current-item="currentItem"
        append-to-body
        v-model="uploadFileVisible"
        @confirm="(filePath) => handleFileUploadConfirm(filePath)"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getTemplateTableLayoutList, refTableDryrun } from "@/api/parameter.js";
import SelectReference from "./select-reference";
import UploadFile from "./upload-file";
import { types } from "../constant";
import { i18n } from "@/lang";
import { mouseover, mouseout, valueMap } from "@/directives/ellipsis.js";
import mixinDryrun from "../mixin/dryrun";

const unwatch = () => {};

const elsyMap = {};

function validateNumber(rule, value, callback) {
  if (value.length > 0) {
    if (!/^[+-]?((\d+(\.\d*)?)|(\.\d+))$/.test(value)) {
      return callback(
        new Error(
          this.$t("flyparam.invalid_input") + "(" + this.$t("flyparam.type_number") + ")"
        )
      );
    }
  }
  if (Number(value) > rule.maxLength) {
    return callback(new Error(this.$t("flyparam.max_number_exceeds")));
  }
  if (Number(value) < -rule.maxLength) {
    return callback(new Error(this.$t("flyparam.number_too_small")));
  }
  callback();
}

function validateHex(rule, value, callback) {
  if (value) {
    if (!/^[0-9a-fA-F]+$/.test(value)) {
      return callback(new Error(i18n.t("flyparam.invalid_input")));
    }

    if (value.length > rule.maxLength) {
      return callback(new Error(i18n.t("flyparam.length_exceeds")));
    }

    if (value.length > 0 && value.length % 2 !== 0) {
      return callback(new Error(i18n.t("flyparam.hex_even")));
    }
  }
  callback();
}

function validateReferenceLength(rule, value, callback) {
  if (value) {
    if (value.length > rule.maxLength) {
      return callback(new Error(i18n.t("flyparam.max_number_exceeds")));
    }

    if (value.length === 0 && rule.nullable === 0 && rule.table.tableType !== 1) {
      return callback(new Error(i18n.t("flyparam.required2")));
    }
  }
  callback();
}

function validateString(rule, value, callback) {
  if (value) {
    if (value.length > rule.maxLength) {
      return callback(new Error(i18n.t("flyparam.length_exceeds")));
    }
  }
  callback();
}

function validateConditionParams(rule, value, callback) {
  if (Object.keys(value).length === 0) {
    debugger;
    return callback(new Error(i18n.t("flyparam.required2")));
  }
  callback();
}

export default {
  name: "DryRun",
  directives: {
    popover: {
      bind(el, binding, vnode) {
        const $el = el.querySelector(".el-input__inner");

        $el.addEventListener(
          "mouseover",
          mouseover.bind(this, $el, binding, vnode),
          false
        );
        $el.addEventListener("mouseout", mouseout, false);
      },
      inserted(el, binding, vnode) {
        const $el = el.querySelector(".el-input__inner");
        const sy = Symbol(vnode);
        $el.sy = sy;
        valueMap[sy] = "";
        elsyMap[binding.value] = sy;
        console.log(elsyMap);
        console.log(valueMap);
      },
      unbind(el, binding) {
        // todo
        const $el = el.querySelector(".el-input__inner");
        delete valueMap["condition0"];
        delete valueMap["operation0"];
        delete valueMap[$el.sy];
        el.removeEventListener("mouseover", mouseover);
        el.removeEventListener("mouseout", mouseout);
      },
    },
  },

  components: {
    SelectReference,
    UploadFile,
  },

  mixins: [mixinDryrun],

  props: {
    profileId: String,
    profileTableList: Array,
    referenceTable: Array,
  },

  data() {
    return {
      types,
      tableId: "",
      activeId: "",
      activeHeaderButton: "Update",
      parameterLabels: [],
      currentParameter: {},
      currentType: "",
      currentCondition: {},
      currentOperation: {},
      mapValueType: {},
      globalId: 3,
      sucNum: 0, // dryRun成功的数目
      failNum: "", // dryRun失败的数目,
      dryrunLoading: false, // dryRun按钮是否加载中
      valueSelectorLoading: false,
      confirmLoading: false, // Confirm按钮是否加载中
      selectReferenceVisible: false, // 选择应用表的组件是否显示
      uploadFileVisible: false, // 上传文件组件是否显示
      showOperations: true,
      conditionOptions: {
        [types.BOOLEAN]: [
          {
            value: 1,
            label: i18n.t("flyparam.true_option"),
          },
          {
            value: 2,
            label: i18n.t("flyparam.false_option"),
          },
        ],
        [types.NUMBER]: [
          { value: 3, label: i18n.t("flyparam.not_set") },
          { value: 4, label: "=" },
          { value: 5, label: "!=" },
          { value: 6, label: "<" },
          { value: 7, label: ">" },
          { value: 8, label: "<=" },
          { value: 9, label: ">=" },
        ],
        [types.REFERENCE]: [
          { value: 12, label: i18n.t("flyparam.in") },
          { value: 13, label: i18n.t("flyparam.not_in") },
        ],
        others: [
          {
            value: 3,
            label: i18n.t("flyparam.not_set"),
          },
          { value: 10, label: i18n.t("flyparam.matches") },
          {
            value: 11,
            label: i18n.t("flyparam.not_matches"),
          },
        ],
      },
      conditions: [
        {
          id: 1,
          select: {},
          value: "",
          active: 1,
          conditionMatcher: "",
          conditionConnector: 1,
          rule: {},
          selectedReferences: [],
        },
      ],
      deleteConditions: [
        {
          id: 1,
          select: {},
          value: "",
          active: 1,
          conditionMatcher: "",
          conditionConnector: 1,
          rules: {},
          cascader: [],
          originParamTrace: "",
          selectedReferences: [],
        },
      ],
      operationTypes: [
        {
          value: 1,
          label: i18n.t("flyparam.update_fields"),
        },
        {
          value: 2,
          label: i18n.t("flyparam.delete_records"),
        },
      ],
      operationType: 1,
      dryrunReady: false,
      showResult: false,
      operations: [{ id: 2, paramId: "", value: "", select: {} }],
      validateConditionSelect(rull, value, callback) {
        if (!value.label) {
          return callback(new Error("Required"));
        }
        callback();
      },
      validateConditionParams: validateConditionParams.bind(this),
    };
  },
  computed: {
    templateId() {
      return this.$route.params.id;
    },
    currentItem() {
      return this[this.currentType] && this[this.currentType].parameter;
    },
    conditionForm() {
      return {
        conditions: this._conditions,
      };
    },
    operationForm() {
      return {
        operations: this.operations,
      };
    },
    _conditions() {
      if (this.operationType === 1) {
        return this.conditions;
      } else {
        return this.deleteConditions;
      }
    },
    conditionString() {
      return JSON.stringify(this._conditions);
    },
    operationsString() {
      return JSON.stringify(this.operations);
    },
    currentReference() {
      return this[this.currentType];
    },
  },

  watch: {
    profileId() {
      this.tableId = this.profileId;
      this.fetchLayoutList();
    },
    conditionString() {
      if (this.dryrunReady) {
        this.showResult = !this.showResult;
        this.dryrunReady = false;
      }
    },
    // operationsString() {
    //   if (this.dryrunReady) {
    //     this.dryrunReady = false
    //   }
    // }
  },
  methods: {
    connectorFilter(val) {
      const connectorValue = {
        1: "AND",
        2: "OR",
      };

      return connectorValue[val];
    },
    download() {
      const a = document.createElement("a");
      a.setAttribute("href", this.downloadUrl);
      a.click();
    },
    addCondition() {
      this._conditions.push({
        id: this.globalId++,
        select: {},
        value: "",
        active: 1,
        conditionMatcher: "",
        conditionConnector: 1,
        selectedReferences: [],
      });
    },
    addOperation() {
      this.operations.push({
        id: this.globalId++,
        paramId: "",
        value: "",
        select: {},
      });
    },
    validateOperationSelect(rull, value, callback) {
      if (this.operationType === 2) {
        return callback();
      }
      if (value && !value.label) {
        return callback(new Error(i18n.t("flyparam.required2")));
      }

      const ids = this.operations.map((_) => _.paramId);

      const duplicateIds = ids.filter((id, index) => ids.indexOf(id) !== index);
      const uniqueDuplicate = [...new Set(duplicateIds)];
      console.log(duplicateIds);
      if (uniqueDuplicate.includes(value.paramId)) {
        return callback(new Error(this.$t("flyparam.duplicate_key")));
      }
      callback();
    },

    handleFileUploadClick(e, id, type) {
      if (type === "condition") {
        this.currentType = "currentCondition";
        this.currentCondition = this._conditions.find((_) => _.id === id);
      } else if (type === "operation") {
        this.currentType = "currentOperation";
        this.currentOperation = this.operations.find((_) => _.id === id);
      }
      this.uploadFileVisible = true;
    },
    handleFileUploadConfirm(filePath) {
      this[this.currentType].value = filePath;
    },

    handleReferenceClick(e, id, type) {
      debugger;
      if (type === "conditions") {
        this.currentType = "currentCondition";
        this.currentCondition = this._conditions.find((_) => _.id === id);
      } else if (type === "operations") {
        this.currentType = "currentOperation";
        this.currentOperation = this.operations.find((_) => _.id === id);
      }

      // debugger

      const current = this[this.currentType];
      // const current = this[this.currentType].find((_) => _.id === id)
      const table = current.parameter?.table;

      this.activeId = current.paramId;
      if (current) {
        if (table) {
          this.selectReferenceVisible = true;
        }
      }
    },
    handleSelectReferenceConfirm(labels, items) {
      if (this.currentType === "currentCondition") {
        this[this.currentType].selectedReferences = items.map((i) => i.id.split("-")[1]);
      }
      this[this.currentType].value = labels;
    },
    handleConnectorCommand(command, item) {
      item.conditionConnector = command;
    },
    fetchLayoutList() {
      getTemplateTableLayoutList(this.$route.params.id, this.tableId).then((data) => {
        this.parameterLabels = data
          .filter((_) => _.type !== 2)
          .map((_) => {
            let table;

            if (_.valueType === 5) {
              debugger;
              const refTable = this.referenceTable.find(
                (table) => table.id === _.refTableSchemaId
              );
              if (refTable) {
                table = {
                  id: _.refTableSchemaId,
                  tableType: refTable.tableType,
                };
              }
            }
            return {
              label: _.label,
              valueType: _.valueType,
              disabled: _.isNewParamAndInTask === 1,
              ..._,
              table,
            };
          });

        this.parameterLabels = this.parameterLabels.filter((_) => {
          if (_.valueType === 5 && _.table.tableType === 1) {
            return false;
          } else {
            return true;
          }
        });
      });
    },
    removeCondition(index) {
      this._conditions.splice(index, 1);
    },
    removeOperation(index) {
      this.operations.splice(index, 1);
    },
    handleClose() {
      unwatch();
      Object.assign(this.$data, this.$options.data());
      this.$nextTick(() => {
        this.$refs.conditionForm.clearValidate();
        this.$refs.operationForm.clearValidate();
      });
    },
    handleOpen() {
      this.tableId = this.profileId;
      this.fetchLayoutList();
    },
    handleTableIdChange() {
      this._conditions = [
        {
          id: 1,
          select: {},
          value: "",
          active: 1,
          conditionMatcher: "",
          conditionConnector: 1,
          rule: {},
        },
      ];
      this.fetchLayoutList();
      // this.fetchReferenceTable()
    },
    handleParameterLabelChange(parameter, item, index) {
      item.parameter = parameter;
      item.conditionMatcher = "";
      item.value = "";
      item.rule = this.getRules(item, "operations");
      item.paramId = parameter.paramId;
      valueMap[elsyMap["condition" + index]] = item.parameter.label;
      console.log(valueMap);
    },
    handleOperationChange(val) {
      if (this.operationType !== val) {
        this.$refs.conditionForm.clearValidate();
        this.dryrunReady = false;
        this.showResult = false;
        this.operationType = val;
        if (val === 2) {
          this.showOperations = false;
        } else if (val === 1) {
          this.showOperations = true;
        }
      }
    },
    async execDryrun(isDryRun) {
      const request = refTableDryrun;
      let conditionValid = true;
      let operationValid = true;

      this.$refs.conditionForm.validate((valid) => {
        conditionValid = valid;
      });
      if (this.operationType === 1 && !isDryRun) {
        this.$refs.operationForm.validate((valid) => {
          operationValid = valid;
        });
      }
      if (conditionValid && operationValid) {
        if (isDryRun) {
          this.dryrunLoading = true;
        } else {
          this.confirmLoading = true;
        }
        const entityConditions = this._conditions.filter(
          (_) => _.select.valueType === "SN"
        );

        const paramConditions = this._conditions.filter(
          (_) => _.select.valueType !== "SN"
        );
        try {
          const res = await request(this.templateId, this.tableId, {
            tableId: this.tableId,
            paramConditions: paramConditions.map((condition) => {
              let conditionValues = [];
              debugger;
              if (condition.select.valueType === types.REFERENCE) {
                if (condition.select.table.tableType === 3) {
                  conditionValues = condition.value.map((item) => {
                    return item.split("-")[1];
                  });
                } else {
                  conditionValues = condition.selectedReferences;
                }
              } else {
                conditionValues = [condition.value];
              }
              const ret = {
                conditionMatcher: condition.conditionMatcher,
                conditionKey: condition.select.label,
                conditionValues,
                conditionConnector: condition.conditionConnector,
                paramId: condition.select.paramId,
                valueType: condition.select.valueType,
              };
              return ret;
            }),
            entityConditions: entityConditions.map((_) => ({
              conditionValue: _.value,
              conditionMatcher: _.conditionMatcher,
              conditionKey: _.select.label,
              conditionConnector: _.conditionConnector,
            })),
            operationType: this.operationType,
            operations:
              this.operationType === 1 && !isDryRun
                ? this.operations.map((_) => ({
                    paramId: _.select.paramId,
                    values: _.select.valueType === types.REFERENCE ? _.value : [_.value],
                  }))
                : [],
            isDryRun,
            orgIds: [],
          });
          if (isDryRun) {
            this.showResult = true;
            this.dryrunReady = true;
            this.sucNum = res.sucNum;
            this.downloadUrl = res.url;
            this.failNum = res.failNum;
            this.dryrunLoading = false;
          } else {
            this.confirmLoading = false;
            this.$emit("update:model-value", false);
            this.$emit("confirm");
          }
          this.$message.success(this.$t("common.message.operation_success"));
        } catch (err) {
          if (isDryRun) {
            this.dryrunLoading = false;
          } else {
            this.confirmLoading = false;
          }
          this.$message.error(err);
        }
      }
    },
    getRules(item) {
      const isOperation = arguments[1] === "operations";
      const { label, nullable, maxLength, table } = item.select;
      console.log(item);
      const rules = {
        [types.HEX]: [
          {
            required: isOperation ? !nullable : true,
            message: this.$t("flyparam.required2", { label: label }),
          },
          { validator: validateHex.bind(this), maxLength: maxLength },
        ],
        [types.NUMBER]: [
          {
            required: isOperation ? !nullable : true,
            message: this.$t("flyparam.required2", { label: label }),
            trigger: "change",
          },
          {
            validator: validateNumber.bind(this),
            trigger: "change",
            maxLength: item.maxLength,
          },
        ],
        [types.REFERENCE]: [
          {
            validator: validateReferenceLength.bind(this),
            maxLength: maxLength,
            nullable: nullable,
            table: item.table,
          },
        ],
        [types.DATE]: [
          {
            required: isOperation ? !nullable : true,
            message: this.$t("flyparam.required2", { label: label }),
            trigger: "change",
          },
        ],
        [types.DATETIME]: [
          {
            required: isOperation ? !nullable : true,
            message: this.$t("flyparam.required2", { label: label }),
            trigger: "change",
          },
        ],
        [types.BOOLEAN]: [
          {
            required: isOperation ? !nullable : true,
            message: this.$t("flyparam.required2", { label: label }),
            trigger: "change",
          },
        ],
        [types.STRING]: [
          {
            required: isOperation ? !nullable : true,
            message: this.$t("flyparam.required2"),
          },
          {
            validator: validateString.bind(this),
            maxLength: maxLength,
          },
        ],
        default: [
          [
            {
              required: isOperation ? !nullable : true,
              message: this.$t("flyparam.required2", { label: label }),
              trigger: "blur",
            },
          ],
        ],
      };
      return rules[item.select.valueType] || rules.default;
    },
    // 筛选出还未选择过的参数，防止重复选择
    filterSelectedParameter(operation) {
      return this.parameterLabels.filter((item) => {
        const ids = this.operations
          .filter((o) => operation.paramId !== o.paramId)
          .map((o) => o.paramId);
        return !ids.includes(item.paramId);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../styles/dryrun.scss";

@include dryrun;

.dryrun-result {
  margin-right: 20px;
  margin-left: 0;
}

.dryrun::v-deep {
  .el-form-item__error {
    padding-top: 0px;
  }

  .el-select-group .el-form-item__error {
    padding-top: 8px;
  }
}
</style>
